import { getRect } from "@/core/tooler";
import { useFactory } from "@/stores/factory";
import { usePop } from "@/stores/pop";

export function init(canvas: HTMLCanvasElement) {
    const factory = useFactory();
    const pop = usePop();
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    const ctx: CanvasRenderingContext2D = canvas.getContext('2d')!;
    const width = canvas.width;
    const height = canvas.height;
    const cellWidth = 10;
    const cellHeight = cellWidth;
    const xTotal = Math.ceil(width / cellWidth);
    const yTotal = Math.ceil(height / cellHeight);

    const curPot = { x: 0, y: 0 };
    let pots: any[] = [];
    const center = { x: 0, y: 0 };
    let drawing = true;
    let edit = false;
    let curIndex = -1;

    function drawGrid() {
        // 绘制水平网格线
        for (let i = 0; i <= yTotal; i++) {
            const cy = height / 2;
            let y = i * cellHeight;
            if (Math.abs(y - cy) < cellHeight / 2) {
                center.y = y;
            }
            ctx.strokeStyle = center.y == y ? '#00ff00' : '#f0f0f0';
            ctx.beginPath();
            ctx.moveTo(0, y);
            ctx.lineTo(width, y);
            ctx.stroke();
        }

        // 绘制垂直网格线
        for (let i = 0; i <= xTotal; i++) {
            const cx = width / 2;
            const x = i * cellWidth;
            if (Math.abs(x - cx) < cellWidth / 2) {
                center.x = x;
            }
            ctx.strokeStyle = center.x == x ? '#ff0000' : '#f0f0f0';
            ctx.beginPath();
            ctx.moveTo(x, 0);
            ctx.lineTo(x, height);
            ctx.stroke();
        }
    }

    function drawPots() {
        ctx.fillStyle = 'rgba(0,0,255,1)';
        pots.forEach(pot => {
            ctx.beginPath();
            ctx.arc(pot.x, pot.y, 3, 0, Math.PI * 2);
            ctx.fill();
        })

    }

    function drawLines() {
        if (pots.length == 0) return;
        ctx.strokeStyle = '#999';
        ctx.beginPath();
        let ary: any[] = edit ? pots : pots.concat(curPot);
        ary.forEach((pot, i) => {
            if (i == 0) {
                ctx.moveTo(pot.x, pot.y);
            }
            else {
                ctx.lineTo(pot.x, pot.y);
            }
        })
        ctx.stroke();
    }

    function drawCurPot() {
        // if (!drawing) return;
        if (drawing) {
            ctx.fillStyle = 'rgba(0,60,120,0.4)';
            ctx.beginPath();
            ctx.arc(curPot.x, curPot.y, 3, 0, Math.PI * 2);
            ctx.fill();
        }
        if (edit) {
            ctx.fillStyle = 'rgba(20,80,30,0.4)';
            ctx.beginPath();
            ctx.arc(curPot.x, curPot.y, 3, 0, Math.PI * 2);
            ctx.fill();
        }

    }

    canvas.addEventListener("mousedown", onDown);
    canvas.addEventListener("mousemove", onMove);
    canvas.addEventListener("mouseup", onUp);

    function onUp() {
        curIndex = -1;
    }

    function onDown(e: any) {
        if (edit) {
            nearPot(e);
            curIndex = pots.findIndex(item => {
                return Math.abs(item.x - curPot.x) < 0.1 && Math.abs(item.y - curPot.y) < 0.1;
            })
            return;
        }
        let x = curPot.x;
        let y = curPot.y;
        if (pots.length == 0) {
            if (x != center.x) {
                pots.push({
                    x: center.x,
                    y: y
                })
            }
            pots.push({
                x: x,
                y: y
            })
        }
        else {
            pots.push({
                x: x,
                y: y
            })
            if (x == pots[0].x) {
                drawEnd();
            }
        }

    }

    function drawEnd() {
        drawing = false;
        edit = true;
        let ary = pots.map(i => {
            return { x: i.x, y: i.y }
        });

        ary.pop();
        // ary.shift();
        ary.reverse();
        ary.forEach((item) => {
            item.x = 2 * center.x - item.x;
        })
        pots = pots.concat(ary);
        console.log("pots", pots);
        // localStorage.setItem("pots", JSON.stringify(pots));

        let rect = getRect(pots);
        // factory.changeSetting(true);
        pop.show("setting");
        factory.changePots(pots);
        factory.changeSize({ width: rect.width, height: rect.height });
    }

    function onMove(e: any) {
        // if (!drawing) return;
        nearPot(e);
        if (edit && curIndex != -1) {
            pots[curIndex].x = curPot.x;
            pots[curIndex].y = curPot.y;
            if (curIndex == 0) {
                pots[pots.length - 1].x = curPot.x;
                pots[pots.length - 1].y = curPot.y;
            }
            else if (curIndex == pots.length - 1) {
                pots[0].x = curPot.x;
                pots[0].y = curPot.y;
            }
        }
    }

    function nearPot(e: any) {
        curPot.x = Math.round(e.clientX / cellWidth) * cellWidth;
        curPot.y = Math.round(e.clientY / cellHeight) * cellHeight;
    }

    function update() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        drawGrid();
        drawLines();
        drawPots();
        drawCurPot();

        requestAnimationFrame(update);
    }

    update();
}